package routers

import (
	_ "gitee.com/CrazyMage/blog-service/docs" //必须加
	"gitee.com/CrazyMage/blog-service/global"
	"gitee.com/CrazyMage/blog-service/internal/middleware"
	"gitee.com/CrazyMage/blog-service/internal/routers/api"
	v1 "gitee.com/CrazyMage/blog-service/internal/routers/api/v1"
	"gitee.com/CrazyMage/blog-service/pkg/limiter"
	"github.com/gin-gonic/gin"
	ginSwagger "github.com/swaggo/gin-swagger"
	"github.com/swaggo/gin-swagger/swaggerFiles"
	"net/http"
	"time"
)

var methodLimiters = limiter.NewMethodLimiter().AddBuckets(
	limiter.LimiterBucketRule{
		Key:          "/auth",
		FillInterval: time.Second,
		Capacity:     10,
		Quantum:      10,
	},
)

func NewRouter() *gin.Engine {
	r := gin.New()
	if global.ServerSetting.RunMode == "debug" {
		r.Use(gin.Logger())
		r.Use(gin.Recovery())
	} else {
		r.Use(middleware.AccessLog())
		r.Use(middleware.Recovery())
	}

	r.Use(middleware.Tracing())
	r.Use(middleware.RateLimiter(methodLimiters))
	r.Use(middleware.ContextTimeout(global.AppSetting.DefaultContextTimeout))
	r.Use(middleware.Translations())

	article := v1.NewArticle()
	tag := v1.NewTag()
	upload := api.NewUpload()
	user := v1.NewUser()
	pay := v1.NewPay()
	ai := v1.NewAi()

	// 调试路由（仅开发环境开放）
	if gin.Mode() != gin.ReleaseMode {
		r.GET("/debug/vars", api.Expvar)
		r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
	}

	r.POST("/upload/file", upload.UploadFile)
	r.POST("/auth", api.GetAuth)

	r.Any("/alipay/notify", pay.Notify)

	// 公开路由（无需鉴权）
	public := r.Group("/users")
	{
		public.POST("/register", user.Register)
		public.POST("/login", user.Login)

	}

	// 鉴权路由
	apiv1 := r.Group("/api/v1")
	apiv1.Use(
		middleware.JWT(),       // JWT 鉴权
		middleware.AccessLog(), // 访问日志
	)
	{
		//用户管理
		apiv1.DELETE("/users/:id", user.Close)

		//标签管理
		apiv1.POST("/tags", tag.Create)       // 创建标签
		apiv1.DELETE("/tags/:id", tag.Delete) // 删除指定标签
		apiv1.PUT("/tags/:id", tag.Update)    // 更新指定标签
		apiv1.GET("/tags", tag.List)          // 获取标签列表

		//文章权限
		apiv1.POST("/articles", article.Create)       // 创建文章
		apiv1.DELETE("/articles/:id", article.Delete) // 删除指定文章
		apiv1.PUT("/articles/:id", article.Update)    // 更新指定文章
		apiv1.GET("/articles/:id", article.Get)       // 获取指定文章
		apiv1.GET("/articles", article.List)          // 获取文章列表

		//支付管理
		apiv1.POST("/alipay/precreate", pay.PreCreate)
		apiv1.GET("/alipay/query", pay.Query)
		apiv1.POST("/alipay/fund", pay.Fund)
		apiv1.GET("/alipay/fundquery", pay.FundQuery)

		//ai功能
		apiv1.POST("/ai/chat", ai.Chat)
		apiv1.POST("/ai/stream/chat", ai.StreamingChat)

		// 静态文件（需鉴权访问）
		r.StaticFS("/static", http.Dir(global.AppSetting.UploadSavePath))
	}

	return r
}
